#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json,re,requests,ssl
from bs4 import BeautifulSoup
from bs4.element import Tag
from datetime import datetime
import configparser
from django.conf import settings

def check_task(name,task):
    storages_state = []
    try:
        rep = requests.get(task,timeout=10)
    except Exception as e:
        print(' %s' % str(e))
        storages_state = [1,1,name+' ConnectTimeout']
        return storages_state
    soup = BeautifulSoup(rep.text,'html.parser')
    if name in ('ooptask'):
        tags = soup.find_all('tr')[2]
    elif name == 'omstask':
        tags = soup.find_all('tr')
        if len(tags) == 1:
            # print('111',next(iter(tags[1].children)))
            # print('this oms tags', tags[1].children.string.find('2020-12-31'))
            storages_state = [0, 1]
            return storages_state
        else:
            for tag in tags[1].children:
                if type(tag) == Tag:
                    if tag.string.find('2020-12-31') == 0:
                        storages_state = [0, 1]
                        return storages_state
            storages_state = [1,1,'oms有新的信息，请检查']
            print('有新的信息，请检查')
            return storages_state
    else:
        tags = soup.find_all('tr')[1]
    tags_list = []
    start_date = datetime.now().strftime('%Y-%m-%d')
    for tag in tags.children:
        if type(tag) == Tag:
            tags_list.append(tag.string)
    if tags_list[1].split()[0] == start_date or tags_list[2].split()[0] == start_date:
        if name in ('aoptask', 'ooptask', 'eoptask'):
            if tags_list[0].split()[0] != '处理成功' or tags_list[3].split()[0] != '处理成功' or tags_list[6].split()[0] != '处理成功':
                storages_state = [1, 1,name+'']
                print('存储过程失败')
            else:
                storages_state = [0, 1]
        else:
            print('-->tags_list',tags_list)
            if tags_list[3] is None or tags_list[4] is None:
                storages_state = [1, 1, name + 'fail']
            else:
                if tags_list[3].split()[0] == '执行完成' or tags_list[4].split()[0] == '执行完成':
                    storages_state = [0, 1]
                else:
                    storages_state = [1, 1, name+'fail']
                    print('存储过程失败')
    else:
        storages_state = [1, 1, '存储过程未执行']
        print('存储过程未执行')
    print('-->storagesState', storages_state)
    return storages_state


def main():
    storages_states = []
    cfg = configparser.ConfigParser()
    cfg.read(settings.CONFIG_PATH,encoding='utf-8')
    print('存储过程:')
    tasks = cfg.items('task')
    for task in tasks:
        storages_states.append(check_task(task[0],task[1]))
    return storages_states
